package FreqCtrl

import (
	"errors"
	"strconv"

	"github.com/garyburd/redigo/redis"
)

//rewrite redis pool
func newPool() *redis.Pool {
	return &redis.Pool{
		MaxIdle:   5,
		MaxActive: 20,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", "localhost:6379")
			if err != nil {
				panic(err.Error())
			}
			return c, err
		},
	}
}

//create redis pool
var pool = newPool()

//Determine if the number of connections is less than the minimum or greater than the maximum value
func judeActConn() {

}

//If redis pool create failed return error ,else return nil
func isPoolCreatSucc() error {
	return nil
}

func getActiveCount() int {
	return pool.ActiveCount()
}

func SetUserFreq(userId string, offerId string, count string) error {
	if userId == "" || offerId == "" || count == "" {
		return errors.New("The argument of the SetUserFreq(string,string,string) is error")
	}

	c := pool.Get()
	if c == nil {
		return errors.New("The connection create failed in the func SetUserFreq(string,string,string)")
	}

	defer c.Close()

	err := c.Send("HINCRBY", userId, offerId, count)
	if err != nil {
		return err
	}

	return nil
}

func GetUserFreq(userId string) (map[string]int, error) {
	if userId == "" {
		return nil, errors.New("The arguement of the GetUserFreq(string) is error")
	}

	c := pool.Get()
	if c == nil {
		return nil, errors.New("The connection create failed in the func GetUserFreq(string)")
	}

	defer c.Close()

	var infomap map[string]int
	infomap = make(map[string]int)

	params, err := redis.Strings(c.Do("HGETALL", userId))
	if err != nil {
		return nil, err
	}

	for i := 0; i < len(params); i += 2 {
		count, err := strconv.Atoi(params[i+1])
		if err != nil {
			return nil, err
		}
		infomap[params[i]] = count
	}
	return infomap, err
}
